package com.morgan.basemodule.view

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent

/**
 *description：
 *<br>author：caowugao
 *<br>time：2021/4/27 0027 21:07
 */
class LifecycleObserverImpl(owner: LifecycleOwner, private val autoClearOnDestroy : Boolean = true): LifecycleObserver {

    private val callbacks : ArrayList<ILifecycleCallback> by lazy { ArrayList() }

    init {
        owner.lifecycle.addObserver(this)
    }

    fun addCallback(callback : ILifecycleCallback) {
        if (!callbacks.contains(callback)) {
            callbacks.add(callback)
        }
    }

    fun removeCallback(callback: ILifecycleCallback) {
        callbacks.remove(callback)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onUICreate() {
        callbacks.forEach {
            it.onCreate()
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onUIResume() {
        callbacks.forEach {
            it.onResume()
        }
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onUIPause() {
        callbacks.forEach {
            it.onPause()
        }
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onUIStop() {
        callbacks.forEach {
            it.onStop()
        }
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onUIDestroy() {
        callbacks.forEach {
            it.onDestroy()
        }
        if (autoClearOnDestroy) {
            callbacks.clear()
        }
    }
}